<template>
    <div class="an-page-children an-address">
        <van-nav-bar
            :title="title"
            left-text=""
            left-arrow
            @click-left="clickBack"
            @click-right="clickDelete"
            >
            <template #right v-if="flag=='1'">
                <van-icon name="delete" size="18" />
            </template>
        </van-nav-bar>

       <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        :add-button-text="buttonText"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelect"
        />
    </div>
</template>

<script>
export default {
  props:{
    flag:{ // 1 为地址管理 2为选择收货地址
      type: String,
      default: '1'
    }
  },
  data() {
    return{
      title:'收货地址管理',
      chosenAddressId: '1',
      list: [], // 地址列表
      buttonText:"新增地址",
      getData:{
        page:1,
        pageSize:20,
        userID:''
      },
      activeAddress:{} // 选中的地址
    };
  },
  mounted() {
    this.anLoad();
  },
  methods:{
    anLoad() {
      if(this.flag ==2) {
        this.buttonText = "确定";
        this.title = "选择收货地址";
      }
      this.getList();
    },

    // 查询列表
    getList() {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      });
      this.getData.userID = this.$store.state.userInfo.id;
      this.$api.userAddressList(this.getData).then(res => {
        this.$toast.clear();
        let nd = [];
        res.records.forEach(element => {
          nd.push({
            id: element.id,
            name: element.consignee,
            tel: element.tel,
            address: element.address,
            areaCode: element.areaCode,
            isDefault: element.isDefault?true:false
          });
        });
        this.list = nd;
      });
    },

    // 选中切换
    onSelect(item) {
      this.activeAddress = item;
    },

    // 删除
    clickDelete() {
      if(this.activeAddress.id) {
        this.$api.userAddressDelete(this.activeAddress.id).then(() => {
          this.getList();
        });
      }
    },

    // 新增地址  确定
    onAdd() {
      if(this.flag ==2) {
        // 选择收货地址 确定
        if(this.activeAddress.id) {
          this.$store.commit('SER_DEFAULTADDRESS', this.activeAddress);
          this.clickBack();
        }
      }else{
        console.log('新增地址');
        this.$router.push({path:'/addressEdit'});
      }
    },

    // 编辑
    onEdit(item) {
      let prom = encodeURI(JSON.stringify(item));
      this.$router.push({path:'/addressEdit', query:{prom: prom}});
    },

    clickBack() {
      this.$router.go(-1);
    }
  }
};
</script>